<?php
	
class Alternatives_model extends CI_model {

	function __construct() {
		parent::__construct();
	}

	function sort($category, $location){
		$table = '';
		$where = '';
		if ($category != 0){
			$table .= ' JOIN alternative_category_tag AS ct ON a.alternative_id = ct.alternative_id ';
			$where .= " AND ct.category_id = ".$category;
		}
		if($location != 0){
			$table .= ' JOIN alternative_location_tag AS lt ON a.alternative_id = lt.alternative_id ';
			$where .= " AND lt.alternative_location_id = ".$location;
		}
		$sql = "SELECT DISTINCT a.* FROM alternative AS a ". $table . " WHERE 1 " . $where . ' ORDER BY a.alternative_id DESC';
		
		$query = $this->db->query($sql);
		$data = array();
		if ($query->num_rows() > 0) {
			foreach ($query->result_array() as $row) {
				$data[] = $row;
			}
		}
		return $data;
	}
	
	
	// Get all alternatives
	function get_alternative($cat) {
		if ($cat)
			$query = $this->db->query("SELECT * FROM alternative AS a JOIN alternative_category_tag AS ct ON
										a.alternative_id = ct.alternative_id 
										WHERE ct.category_id = ? ORDER BY a.alternative_id DESC",$cat);
		else
			$query = $this->db->query("SELECT * FROM alternative ORDER BY alternative_id DESC");
		$data = array();
		if ($query->num_rows() > 0) {
			foreach ($query->result_array() as $row) {
				$data[] = $row;
			}
		}
		return $data;
	}
	
	
	// Get all alternative locations
	function get_alternative_location() {
		$query = $this->db->query("SELECT * FROM alternative_location");
		$data = array();
		if ($query->num_rows() > 0) {
			foreach ($query->result_array() as $row) {
				$data[] = $row;
			}
		}
		return $data;
	}
	
	// Get all alternative category tags
	function get_alternative_category_tag() {
		$query = $this->db->query("SELECT * FROM alternative_category_tag");
		$data = array();
		if ($query->num_rows() > 0) {
			foreach ($query->result_array() as $row) {
				$data[] = $row;
			}
		}
		return $data;
	}
	
	// Get all location category tags
	function get_alternative_location_tag() {
		$query = $this->db->query("SELECT * FROM alternative_location_tag");
		$data = array() ;
		if ($query->num_rows() > 0) {
			foreach ($query->result_array() as $row) {
				$data[] = $row;
			}
		}
		return $data;
	}
}

?>